from django.shortcuts import render, redirect, HttpResponse
from phone_info_app.utils.Pagination import Pagination
from phone_info_app.utils.code import check_code
from phone_info_app.utils.form import PhoneModelForm, AdminModelForm, LoginForm, ResetForm, VerityForm
from phone_info_app import models

brands_list = models.AllPhones.objects.values_list('品牌', flat=True).distinct()
verity = 0


# 管理员登录
def login(request):
    global verity
    verity += 1
    if verity > 3:
        if request.method == "GET":
            form = VerityForm()
            return render(request, 'login.html', {"form": form, 'verity': verity})
        form = VerityForm(data=request.POST)
    else:
        if request.method == "GET":
            form = LoginForm()
            return render(request, 'login.html', {"form": form, 'verity': verity})
        form = LoginForm(data=request.POST)
    if form.is_valid():
        # 验证成功，获取用户名和密码
        print(form.cleaned_data)
        if verity > 3:
            # 验证码的校验
            user_input_code = form.cleaned_data.pop('code')
            code = request.session.get("image_code", "")
            if code.upper() != user_input_code.upper():
                form.add_error("code", "验证码错误")
                return render(request, "login.html", {"form": form, 'verity': verity})
            admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        else:
            admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error("password", "用户名或密码错误")
            return render(request, 'login.html', {"form": form, 'verity': verity})

        # 用户名和密码输入正确
        # 网站生成随机字符串，写到用户浏览器的cookie中，再写到session中
        verity = 0
        request.session["info"] = {"id": admin_object.id, "username": admin_object.username}
        request.session.set_expiry(60 * 60 * 24 * 7)
        return redirect('/index/')
    return render(request, 'login.html', {"form": form, 'verity': verity})

# 验证码
def image_code(request):
    """图片验证码"""
    # 调用pillow函数，生成图片
    img, code_string = check_code()
    print(code_string)

    # 写入到session中，以便于后续获取验证码在进行校验
    request.session["image_code"] = code_string
    # 给session设置60s超时
    request.session.set_expiry(60)

    # 写入内存(Python3)
    from io import BytesIO
    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())


# 管理员注册
def admin_sign(request):
    if request.method == "GET":
        form = AdminModelForm()
        return render(request, 'admin_sign.html', {"form": form})
    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        # 验证成功，获取用户名和密码
        print(form.cleaned_data)
        # 验证用户名是否存在
        if models.Admin.objects.filter(username=form.cleaned_data.get('username')).exists():
            form.add_error("username", "用户名已存在。")
            return render(request, "admin_sign.html", {"form": form})

        # 两次密码的校验
        confirm_password = form.cleaned_data.pop('confirm_password')
        password = form.cleaned_data.get("password")
        if password != confirm_password:
            form.add_error("confirm_password", "密码不一致,请确认后输入。")
            return render(request, "admin_sign.html", {"form": form})
        form.save()
        admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        # 网站生成随机字符串，写到用户浏览器的cookie中，再写到session中
        request.session["info"] = {"id": admin_object.id, "username": admin_object.username}
        request.session.set_expiry(60 * 60 * 24 * 7)
        return redirect('/index/')
    return render(request, 'admin_sign.html', {"form": form})


# 密码重置
def admin_reset(request):
    print("successful")
    print(request.session['info'].get('username'))
    old_info = models.Admin.objects.filter(username=request.session['info'].get('username')).first()
    print(old_info)
    if request.method == "GET":
        form = ResetForm(instance=old_info)
        context = {
            "form": form,
        }
        return render(request, 'admin_reset.html', context)
    form = ResetForm(instance=old_info, data=request.POST)
    if form.is_valid():
        # 验证成功，获取用户名和密码
        print(form.cleaned_data)
        # 两次密码的校验
        confirm_password = form.cleaned_data.pop('confirm_password')
        password = form.cleaned_data.get("password")
        if password != confirm_password:
            form.add_error("confirm_password", "密码不一致,请确认后输入。")
            return render(request, "admin_reset.html", {"form": form})
        form.save()
        request.session.clear()
        admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        # 网站生成随机字符串，写到用户浏览器的cookie中，再写到session中
        request.session["info"] = {"id": admin_object.id, "username": admin_object.username}
        request.session.set_expiry(60 * 60 * 24 * 7)
        return redirect('/index/')
    return render(request, 'admin_sign.html', {"form": form})


# 注销
def admin_logout(request):
    """注销"""
    request.session.clear()
    return redirect('/index/')


# 主页
def index_list(request):
    query = {}
    search_data = request.GET.get('q', '')
    if search_data:
        query["手机名称__contains"] = search_data
    new_info = models.AllPhones.objects.filter(**query).order_by('-上市日期')[0:10]
    context = {
        'brands_list': brands_list,
        'new_info': new_info,
        "search_data": search_data,
    }
    return render(request, 'index.html', context)


# 获取该品牌的手机信息
def phone_list(request, brand):
    query = {}
    search_data = request.GET.get('q', '')
    if search_data:
        query["手机名称__contains"] = search_data
    query['品牌'] = brand
    qs = models.AllPhones.objects.filter(**query).order_by('-id')
    phones_list = Pagination(request, qs)
    context = {
        'phone_list': phones_list.page_queryset,
        "page_string": phones_list.html(),
        "search_data": search_data,
        'brands_list': brands_list,
        'brand': brand,
    }
    return render(request, 'phone_list.html', context)


# 获取该手机的参数信息
def phone_info(request, name):
    phones_info = models.AllPhones.objects.filter(手机名称=name).values()[0]
    brand = phones_info['品牌']
    context = {
        'phone_info': phones_info,
        'id': phones_info['id'],
        'brands_list': brands_list,
        'brand': brand,
    }
    return render(request, 'phone_info.html', context)


# 编辑该手机参数的信息
def phone_edit(request, nid):
    old_info = models.AllPhones.objects.filter(id=nid).first()
    brand = old_info.品牌
    print(old_info.手机名称)
    if request.method == "GET":
        form = PhoneModelForm(instance=old_info)
        context = {
            "form": form,
            'brands_list': brands_list,
            'brand': brand,
        }
        return render(request, 'phone_edit.html', context)
    form = PhoneModelForm(data=request.POST, instance=old_info)
    if form.is_valid():
        form.save()
        return redirect('/phone/{}/'.format(old_info.品牌))
    context = {
        "form": form,
        'brands_list': brands_list,
        'brand': brand,
    }
    return render(request, 'phone_edit.html', context)
